package cn.zniot.so.application.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

/**
 * 线程服务管理类
 */
public class ServiceManager {
	private final Logger logger = Logger.getLogger(ServiceManager.class);
	
	public static final byte SERVICE_Zniot = 1;

	public static final byte SERVICE_SEARCHTASK = 2;

	private static ServiceManager instance = null;

	private List<IService> services = new ArrayList<IService>(2);

	private ServiceManager() {
		this.init();
	}

	public synchronized static ServiceManager getInstance() {
		if (instance == null) {
			instance = new ServiceManager();
		}
		return instance;
	}

	private void init() {
	    if (logger.isDebugEnabled()) {
	        logger.debug("start up thread service class");
        }
		this.services.add(new HeartBeatThread());// 服务器给盒子发送心跳的线程
	}

	/**
	 * 启动发布服务
	 */
	public void startUpService() {
		for (int i = 0, j = this.services.size(); i < j; i++) {
			this.services.get(i).startUp();
		}
	}

	/**
	 * 终止发布服务
	 */
	public void shutDown() {
		for (int i = 0, j = this.services.size(); i < j; i++) {
			this.services.get(i).shutDown();
		}
		if (logger.isDebugEnabled()) {
			logger.debug("service shutdown!");
		}
	}

	/**
	 * 暂停指定服务
	 */
	public void pause(byte serviceID) {
		IService service = null;
		for (int i = 0, j = this.services.size(); i < j; i++) {
			service = this.services.get(i);
			if (service.getService() == serviceID) {
				break;
			}
			service = null;
		}
		service.pause();
	}

	/**
	 * 唤醒指定服务
	 */
	public void wakeup(byte serviceID) {
		IService service = null;
		for (int i = 0, j = this.services.size(); i < j; i++) {
			service = this.services.get(i);
			if (service.getService() == serviceID) {
				break;
			}
			service = null;
		}
		service.wakeup();
	}

	/**
	 * 获取指定服务
	 */
	public IService getService(byte serviceID) {
		IService service = null;
		for (int i = 0, j = this.services.size(); i < j; i++) {
			service = this.services.get(i);
			if (service.getService() == serviceID) {
				break;
			}
			service = null;
		}
		return service;
	}
	
}
